package thread.lockAndCondition;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Description: Cache demo
 * Created by E440 on 2017/4/24.
 */
public class CacheDemo {
    private int sn=0;
    private  Object value=null;

    public static void main(String[] args) {
        final CacheDemo cacheDemo=new CacheDemo();
        for (int i = 0; i < 3; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(cacheDemo.getData());
                }
            }).start();
        }

    }


    private ReadWriteLock readWriteLock=new ReentrantReadWriteLock();

    public Object getData(){

        readWriteLock.readLock().lock();
        try {
            if(value==null){
                readWriteLock.readLock().unlock();
                readWriteLock.writeLock().lock();
                try {
                    sn++;
                    if(value==null){
                        value="useful data:"+sn;
                    }
                }finally {
                    readWriteLock.writeLock().unlock();
                }
                readWriteLock.readLock().lock();
            }
        }finally {
            readWriteLock.readLock().unlock();
        }
        return  value;
    }
}
